import { defineStore } from 'pinia'
import api from '../api'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user') || '{}')
  }),
  getters: {
    isAuthenticated: (state) => !!state.token
  },
  actions: {
    async login(username: string, password: string) {
      try {
        const response = await api.post('/auth/login/', {
          username,
          password
        })
        const token = response.data.access
        localStorage.setItem('token', token)
        
        // 获取用户信息
        const userResponse = await api.get('/user/profile/', {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        this.token = token
        this.user = userResponse.data
        localStorage.setItem('user', JSON.stringify(userResponse.data))
        
        return true
      } catch (error) {
        console.error('Login failed:', error)
        return false
      }
    },
    
    logout() {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      this.token = ''
      this.user = {}
    },
    
    async register(username: string, password: string, email: string) {
      try {
        await api.post('/auth/register/', {
          username,
          password,
          email
        })
        return true
      } catch (error) {
        console.error('Registration failed:', error)
        return false
      }
    }
  }
})